package com.wxh.multithread;

/**
 * @ClassName: UnsafeBank
 * @Description: 不安全取钱
 * @Author wxh
 * @Date: 2022/1/11 10:00
 * @Version V1.0.0
 * @Since 1.8
 */
public class UnsafeBank {
    public static void main(String[] args) {
        Account account = new Account(100, "结婚基金");

        // 创建线程
        DrawMoney you = new DrawMoney(account, 50, "你");
        DrawMoney youWife = new DrawMoney(account, 100, "你的妻子");

        you.start();
        youWife.start();

    }
}

/**
 * 账户
 */
class Account{
    /**
     * 余额
     */
    int money;
    /**
     * 卡名称
     */
    String cardName;

    public Account(int money, String cardName) {
        this.money = money;
        this.cardName = cardName;
    }
}

/**
 * 取钱
 */
class DrawMoney extends Thread{
    Account account;
    /**
     * 取了多少元钱
     */
    int drawMoney;
    /**
     * 手里还有多少元钱
     */
    int nowMoney;

    public DrawMoney(Account account, int drawMoney, String name) {
        super(name);
        this.account = account;
        this.drawMoney = drawMoney;
    }

    @Override
    public void run() {
        // synchronized 默认锁this，这里要锁定对象，一般是变化的对象synchronized(obj){}
        synchronized (account){
            // 判断手里还有没有钱
            if(account.money - drawMoney < 0){
                System.out.println(Thread.currentThread().getName() +"钱不够了, 取不了");
                return;
            }

            // 模拟延时
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 卡内余额 = 余额 - 你取的钱
            account.money =  account.money - drawMoney;
            // 你手里的钱 = 你手里的钱 + 你取的钱
            nowMoney = nowMoney + drawMoney;

            System.out.println(account.cardName + "余额为：" + account.money);
            // Thread.currentThread().getName() = this.getName()
            System.out.println(this.getName()+"手里的钱："+nowMoney);
        }
    }
}
